package vip.ola.code.ctrl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vip.ola.code.common.ctrl.BaseController;
import vip.ola.code.common.service.RpcCommonService;
import vip.ola.core.common.annotation.MethodLog;
import vip.ola.core.common.constant.Constant;
import vip.ola.core.common.constant.RetEnum;
import vip.ola.core.common.domain.BizResponse;
import vip.ola.core.common.domain.PayResponse;
import vip.ola.core.common.util.GoogleAuthenticator;
import vip.ola.core.entity.code.CodeUser;

import javax.servlet.http.HttpServletRequest;

import static vip.ola.core.common.constant.CodeConstant.CODE_STATUS_OK;
import static vip.ola.core.common.constant.Constant.STATUS_NO;
import static vip.ola.core.common.constant.Constant.STATUS_YES;

/**
 * 代理商安全中心
 */
@RestController
@RequestMapping(Constant.CODE_CONTROLLER_ROOT_PATH + "/security")
public class SecurityCenterController extends BaseController {

    @Autowired
    private RpcCommonService rpcCommonService;

    @Value("${config.payUrl}")
    protected String payUrl;

    /**
     * 得到用户谷歌验证二维码
     *
     * @return
     */
    @RequestMapping("/google_qrcode")
    public ResponseEntity<?> getGoogleAuthQrCode() {
        CodeUser codeUser = rpcCommonService.codeUserService.getById(getUser().getId());
        String googleAuthSecretKey = codeUser.getGoogleAuthSecret();
        if (StringUtils.isBlank(googleAuthSecretKey)) {
            googleAuthSecretKey = GoogleAuthenticator.generateSecretKey();
            CodeUser updateUser = new CodeUser();
            updateUser.setId(codeUser.getId());
            updateUser.setGoogleAuthStatus(STATUS_NO);
            updateUser.setGoogleAuthSecret(googleAuthSecretKey);
            boolean result = rpcCommonService.codeUserService.update(updateUser);
            if (!result) {
                return ResponseEntity.ok(PayResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
            }
        }
        String qrcode = GoogleAuthenticator.getQRBarcode("ola-code(" + codeUser.getUsername() + ")", googleAuthSecretKey);
        String qrcodeUrl = payUrl + "/qrcode_img_get?url=" + qrcode + "&widht=200&height=200";
        return ResponseEntity.ok(PayResponse.buildSuccess(qrcodeUrl));
    }

    /**
     * 绑定谷歌验证
     *
     * @return
     */
    @RequestMapping("/google_bind")
    @MethodLog(remark = "绑定谷歌验证")
    public ResponseEntity<?> bindGoogleAuth(HttpServletRequest request) {
        // 获取传的验证码
        Long code = getLongRequired("code");
        if (!checkGoogleCode(getUser().getId(), code)) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_GOOGLECODE_NOT_MATCH));
        }
        // 修改数据中绑定状态
        CodeUser updateUser = new CodeUser();
        updateUser.setId(getUser().getId());
        updateUser.setGoogleAuthStatus(STATUS_YES);
        boolean result = rpcCommonService.codeUserService.update(updateUser);
        if (!result) {
            return ResponseEntity.ok(PayResponse.build(RetEnum.RET_MCH_GOOGLEAUTH_SECRETKEY_BIND_FAIL));
        }
        return ResponseEntity.ok(PayResponse.buildSuccess());
    }

    /**
     * 设置登录验证方式
     *
     * @return
     */
    @RequestMapping("/login_set")
    @MethodLog(remark = "设置登录验证方式")
    public ResponseEntity<?> setLogin(HttpServletRequest request) {
        Integer loginSecurityType = getIntegerRequired("loginSecurityType");
        Long code = getLongRequired("code");
        if (!checkGoogleCode(getUser().getId(), code)) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_GOOGLECODE_NOT_MATCH));
        }
        if (loginSecurityType == 1) {    // 登录密码+谷歌验证组合
            CodeUser codeUser = rpcCommonService.codeUserService.getById(getUser().getId());
            if (!CODE_STATUS_OK.equals(codeUser.getGoogleAuthStatus())) {
                // 没有绑定谷歌
                return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_GOOGLEAUTH_NOT_BIND));
            }
        }
        CodeUser updateUser = new CodeUser();
        updateUser.setId(getUser().getId());
        updateUser.setLoginSecurityType(loginSecurityType);
        boolean result = rpcCommonService.codeUserService.update(updateUser);
        if (!result) {
            return ResponseEntity.ok(PayResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
        }
        return ResponseEntity.ok(PayResponse.buildSuccess());
    }

    /**
     * 验证谷歌验证码
     *
     * @param code
     * @return
     */
    boolean checkGoogleCode(Long userId, Long code) {
        CodeUser codeUser = rpcCommonService.codeUserService.getById(userId);
        String googleAuthSecretKey = codeUser.getGoogleAuthSecret();
        return checkGoogleCode(googleAuthSecretKey, code);
    }

}